package com.glut.library.controller;

import com.glut.library.entity.Book;
import com.glut.library.entity.Users;
import com.glut.library.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
/**
 *  管理端用户管理控制器
 * @author Stubborn
 * createtime 2024/12/17 16:06
 */


@RestController
@RequestMapping("/users")
public class UsersManagementController {

    @Autowired
    private IUsersService usersService;

    // 获取所有用户
    @GetMapping("/all")
    public ResponseEntity<List<Users>> getAllUsers() {
        List<Users> usersList = usersService.list();
        return ResponseEntity.ok(usersList);
    }

    // 搜索书籍
    @GetMapping("/search")
    public List<Users> searchBooks(@RequestParam(required = false) String query) {
        return usersService.searchUsers(query); // 直接返回搜索结果
    }

    // 新增用户
    @PostMapping("/add")
    public ResponseEntity<String> createUser (@RequestBody Users user) {
        boolean saved = usersService.save(user);
        return saved ? ResponseEntity.ok("用户创建成功") : ResponseEntity.badRequest().body("用户创建失败");
    }

    // 更新用户
    @PutMapping("/update/{id}")
    public ResponseEntity<String> updateUser (@PathVariable Integer id, @RequestBody Users user) {
        user.setId(id); // 确保 ID 是正确的
        boolean updated = usersService.updateById(user);
        return updated ? ResponseEntity.ok("用户更新成功") : ResponseEntity.status(HttpStatus.NOT_FOUND).body("用户未找到");
    }

    // 删除用户
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> deleteUser (@PathVariable Integer id) {
        boolean removed = usersService.removeById(id);
        return removed ? ResponseEntity.ok("用户删除成功") : ResponseEntity.status(HttpStatus.NOT_FOUND).body("用户未找到");
    }
}
